package com.aurora.gulimall.product.web;

import com.aurora.gulimall.product.entity.CategoryEntity;
import com.aurora.gulimall.product.service.CategoryService;
import com.aurora.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
public class IndexController {
    @Autowired
    CategoryService categoryService;
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    StringRedisTemplate stringRedisTemplate;


    @GetMapping({"/","/index.html"})
    public String indexPage(Model model){
        // 1、查出所有的1级分类
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Categorys();
        model.addAttribute("categorys",categoryEntities);
        return "index";
    }

    @ResponseBody
    @GetMapping("/index/catalog.json")
    public Map<String, List<Catelog2Vo>> getCatalogJson(){
        Map<String, List<Catelog2Vo>> map = categoryService.getCatalogJson();
        return map;
    }


   @ResponseBody
   @GetMapping("/hello")
   public String hello(){
        //1、获取可重入锁,只要锁名一样，就是同一把锁
       RLock lock = redissonClient.getLock("my-lock");
       try {
           //2、加锁 默认锁ttl 30s
           //2.1 锁的自动续期，如果业务超长，运行期间自动给锁续上新的30s。不用担心业务时间长，锁自动过期删除
           //2.2 加锁业务只要完成运行，就不会给当前锁续期，即使不手动解锁，锁默认在30s以后自动删除
//           lock.lock();//阻塞式等待
//           推荐使用自定义时间加锁
           lock.lock(10, TimeUnit.SECONDS);//10秒自动解锁，锁超时不会自动续期  自动解锁时间一定要大于业务执行时间
           //1、如果传递了锁的超时时间，就发送给redis执行脚本，进行占锁，默认超时就是指定的时间
           //2、未指定超时时间，就使用30*1000【LockWatchdogTimeout默认时间】
//                    只要占锁成功，就会启动定时任务【重新给锁设置过期时间 】
//           internalLockLeaseTime[看门狗时间] / 3，每10s续期
           System.out.println("加锁成功，执行业务代码"+Thread.currentThread().getId());
           Thread.sleep(30000);
       } catch (Exception e) {
           throw new RuntimeException(e);
       }finally {
           //3、解锁
           System.out.println("释放锁。。。"+Thread.currentThread().getId());
           lock.unlock();
       }

       return "hello";
    }


    @ResponseBody
    @GetMapping("/write")
    public String writeValue(){
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("test");
        String s = "";
        RLock rLock = readWriteLock.writeLock();
        try {
            rLock.lock();
            s = UUID.randomUUID().toString();
            Thread.sleep(30000);
            stringRedisTemplate.opsForValue().set("writeValue",s);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            rLock.unlock();
        }
        return s;
    }

    @ResponseBody
    @GetMapping("/read")
    public String readValue(){
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("test");
        String s = "";
        RLock rLock = readWriteLock.readLock();
        try {
           s =  stringRedisTemplate.opsForValue().get("writeValue");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            rLock.unlock();
        }
        return s;
    }

    /**
     * 放假锁门，五个班都走完才能锁门
     * */

    @GetMapping("/lockDoor")
    @ResponseBody
    public String lockDoor() throws InterruptedException {
        RCountDownLatch door = redissonClient.getCountDownLatch("door");
        door.trySetCount(3);
        door.await();
        return "放假了...";
    }

    @GetMapping("/lock/{id}")
    @ResponseBody
    public String goGo(@PathVariable Long id){
        RCountDownLatch door = redissonClient.getCountDownLatch("door");
        door.countDown();
        return id+"班放假了";
    }


    @GetMapping("/park")
    @ResponseBody
    public String park() throws InterruptedException {
        RSemaphore zoo = redissonClient.getSemaphore("zoo");
        zoo.acquire();
        return "ok";
    }

    @GetMapping("/go")
    @ResponseBody
    public String go() throws InterruptedException {
        RSemaphore zoo = redissonClient.getSemaphore("zoo");
        zoo.release();
        return "ok";
    }



}
